﻿#include "qdialoglogin.h"
#include "ui_qdialoglogin.h"
#include<QFile>
#include<QDir>
#include<QCryptographicHash>
#include<QMessageBox>
#include<QPushButton>
#include<QPainter>
#include<QPixmap>
#include <QGraphicsDropShadowEffect>
#include<QDebug>
#include<QMovie>
#include<QApplication>

#include<ChatWidget.h>
#include"signup.h"
#include"ui_signup.h"
#include"safe.h"


QDialogLogin::QDialogLogin(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::QDialogLogin)
{
     setAttribute(Qt::WA_ShowModal,true);//设置类产生的对象为非模态
    ui->setupUi(this);
    //qt实现动图播放
    QMovie *movie=new QMovie("C:/Qt/PROJECT_LEE/images/log.gif");
//     QMovie *movie=new QMovie(:/../PROJECT_LEE/images/log.gif);  //资源
    ui->gif->setMovie(movie);
    movie->start();

    //设置图片
    QPixmap pic;
      QSize size;//画框大小
      pic.load("C:/Qt/PROJECT_LEE/images/ff.png");
      //设置图片显示尺寸
      size.setHeight(ui->label_bg->height());
      size.setWidth(ui->label_bg->width());
      //照片处理
      pic=pic.scaled(size,Qt::IgnoreAspectRatio);
      //显示
      ui->label_bg->setPixmap(pic);

      //设置阴影
      QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this);
      shadow->setOffset(-3, 0);
      shadow->setColor(QColor("#888888"));
      shadow->setBlurRadius(30);
      ui->label_bg->setGraphicsEffect(shadow);

    ui->editPSWD->setEchoMode(QLineEdit::Password);
    this->setWindowFlags(Qt::SplashScreen);//设置为登录界面
    this->setWindowFlags(Qt::FramelessWindowHint);//无边框但在任务栏上显示标题


    readFile();
    ui->comboBox->setCurrentIndex(ui->comboBox->count()-1);

    //初始化数据库
    sqlite_Init();
}

QDialogLogin::~QDialogLogin()
{
    delete ui;
}


//数据库初始化函数，每次需要对数据库进行操作的时候都需要先调用它进行初始化
void sqlite_Init()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("user.db");
    if(!db.open())
    {
        qDebug()<<"open error";
    }
    //create excle
    QString createsql=QString("create table if not exists user(id integer primary key autoincrement,"
                        "username ntext unique not NULL,"
                        "password ntext not NULL)");
    QSqlQuery query;
    if(!query.exec(createsql)){
        qDebug()<<"table create error";
    }
    else{
        qDebug()<<"table create success";
    }
}

//获取用户名
QString QDialogLogin::GetUserName()
{
    return ui->comboBox->currentText().trimmed();
}

QString QDialogLogin::GetUserPswd()
{

    QString pswd=ui->editPSWD->text().trimmed();
    m_pswd=pswd;
     return 0;
}


//登录
void QDialogLogin::on_btnOK_clicked()
{


     sqlite_Init();
     //读取comoBox上的名字
    QString user=ui->comboBox->currentText().trimmed();//消掉开头和结尾的空格
    //读取editPSWD上的密码
    QString pswd=ui->editPSWD->text().trimmed();
    //对获得的密码pswd进行处理
    QString encrptPSWD=encrypt(pswd);

    QString sql=QString("select * from user where username='%1' and password='%2'")
                 .arg(user).arg(pswd);

    //获取改用户名的密码 GetPSWDByName;
    QString rigthPswd=encrypt(m_pswd);
    m_user=GetUserName();

//    创建执行语句对象
           QSqlQuery query(sql);
           //判断执行结果
           if(!query.next())
           {
               qDebug()<<"Login error";
               QMessageBox::information(this,"登录认证","登录失败,账户或者密码错误");
           }
           else
           {
    if(ui->chkBoxSave->isChecked())
    {
        ui->comboBox->addItem(ui->comboBox->currentText());//把当前文本加入
        writeFile();
        qDebug("66666666666666666666");
    }

    ChatWidget *chat=new ChatWidget(nullptr,m_user);
    QDialogLogin *Login=new QDialogLogin;
    Login ->deleteLater();
    Login=nullptr;
    chat->show();
    this->close();
    qDebug()<<"Login success";
    QMessageBox::information(this,"登录认证","登录成功");

    }
}

//sign up
void QDialogLogin::on_pushButton_clicked()
{
//关闭登录界面
    this->close();
//打开注册界面
   Signup *S =new Signup;
 S->show();

}



//删除用户名
void QDialogLogin::on_btn_delete_username_clicked()
{
  if(0==ui->comboBox->count())
  {
      ui->comboBox->setCurrentText("");
  }else
  {
    ui->comboBox->removeItem(ui->comboBox->currentIndex());
    this->m_IsComboxNeedChange=true;
  }
}

//关闭界面
void QDialogLogin::on_btnCancel_clicked()
{

    if(m_IsComboxNeedChange)//是否需要更新Combox里存的用户
         writeFile();
     this->close();

}


QString QDialogLogin::user() const
{
    return m_user;
}

void QDialogLogin::setUser(const QString &user)
{
    m_user = user;
}

bool QDialogLogin::readFile()
{
    QString currentPath=QDir::currentPath();
    QFile file(currentPath+"/init.dat");
    if(!file.exists())
    {
        return false;
    }



    if(!file.open(QIODevice::ReadOnly))
    {
        return false;
    }

      QDataStream in(&file);
      int count;
      in>>count;
      for(int i=0;i<count;i++)
      {
          QString str;
          in>>str;
          ui->comboBox->addItem(str);
      }
      return true;


}

bool QDialogLogin::writeFile()
{
    //保存用户名到文件里
    QString currentPath=QDir::currentPath();
    QFile file(currentPath+"/init.dat");
    if(!file.open(QIODevice::WriteOnly|QIODevice::Truncate))
    {
        return false;
    }

    QDataStream out(&file);
    out<<ui->comboBox->count();
   for(int i=0;i<ui->comboBox->count();i++)
   {
       out<<ui->comboBox->itemText(i);

   }
   file.close();
   return true;

}

QString QDialogLogin::encrypt(const QString &str)
{
    //字符串MD5加密
    QByteArray btArray;
    btArray.append(str);
    QCryptographicHash hash(QCryptographicHash::Md5);
    hash.addData(btArray);
    QByteArray  resultArray=hash.result();
    QString md5=resultArray.toHex();//转化成十六进制
    return md5;

}

void QDialogLogin::mousePressEvent(QMouseEvent *event)
{
    //event->globalPos()获取鼠标以电脑屏幕左上角为原点的向量
    if(event->button()==Qt::LeftButton)
    {
        this->m_moveing=true;
        m_lastPos=event->globalPos()-pos();//使用向量的减法获得鼠标相对于窗口的位置

    }
    return  QDialog::mousePressEvent(event);

}

void QDialogLogin::mouseMoveEvent(QMouseEvent *event)
{
    //在mouseMoveEvent 里event->button()返回的引进事件的button永远是Qt::NoButton!!
    if(m_moveing && (event->buttons()&&Qt::LeftButton))//左键被按下
    {
        move(event->globalPos()-m_lastPos);
       //m_lastPos=event->globalPos()-pos();//使用向量的减法获得鼠标相对于窗口的位置
    }
   return QDialog::mouseMoveEvent(event);
}

void QDialogLogin::mouseReleaseEvent(QMouseEvent *event)
{
   Q_UNUSED(event);
   m_moveing=false;
}


void QDialogLogin::on_safeBtn_clicked()
{
    this->hide();
    safe *ss=new safe;
    ss->setWindowModality(Qt::ApplicationModal);
    ss->show();
}
